﻿using AutoMapper;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.BasicData.API.Write.Application.User
{
    public class UserAddCommandHandler : IRequestHandler<UserAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_User> userRepository;
        private readonly IMapper mapper;

        public UserAddCommandHandler(IBaseRepository<T_User> userRepository, IMapper mapper)
        {
            this.userRepository = userRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(UserAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var model = userRepository.GetAll().AsNoTracking().Where(p => p.UserName == request.UserName);
            if (model.Count() > 0)
            {
                result.Code = APIEnum.faile;
                result.Message = "用户名已存在";
                return await Task.FromResult(result);
            }
            var user = mapper.Map<T_User>(request);
            user.CreateUserName = "张三";
            user.Password = 12345678.GetMD5();
            user.CreateTime = DateTime.Now;
            result.Code = APIEnum.ok;
            result.Message = "添加成功";
            result.Data = await userRepository.Add(user);
            return await Task.FromResult(result);

        }
    }
}
